#include "webserver.h"
#include "w5500.h"
#include <intrins.h>

#define ISO_G               0x47  		//"G" ascii码
#define ISO_E               0x45 		//"E" ascii码
#define ISO_T               0x54 		//"T" ascii码

//HTTP报文
static const unsigned char code webdata[] = {
"HTTP 1.0 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Pragma: no-cache\r\n\r\n"
"<html>\r\n"
"<head>\r\n"
"<tiltle>xxxx</tiltle>\r\n"
"<head>\r\n"
"<body>\r\n"
"<center>\r\n"
"<hl>xxxx</hl>\r\n"
"<br>\r\n"
"<hr>\r\n"
"<font size=14>\r\n"
"my name is huang.chaomeng\r\n"
"</font>\r\n"
"<hr>\r\n"
"<font size=14>\r\n"
"Email:huangchaomeng@qq.com\r\n"
"<hr>\r\n"
"<font size=24>\r\n"
"hello world\r\n"
"</font>\r\n"
"</center>\r\n"
"</body>\r\n"
"</html>\r\n\0"
};
static unsigned char buffer[350];  	//数据缓冲区

//检测是否HTTP请求，加入是HTTP请求头部前三位是"GET"
static unsigned char check_http_header(unsigned char *pbuf, unsigned int mxsize)
{
	if(mxsize < 3)
		return 0;
	if(pbuf[0] != ISO_G)
		return 0;
	if(pbuf[1] != ISO_E)
		return 0;
	if(pbuf[2] != ISO_T)
		return 0;
	return 1;
}

static void web_reset(void)
{
	unsigned char i;
	socket_close(SOCKET0);
	for(i = 0; i < 3; i++)
		_nop_();
	socket_init(SOCKET0, 80);
	socket_listen(SOCKET0);
}

//获取字符串长度
static unsigned int __strlen(const unsigned char *pdat)
{
	unsigned int ret = 0;
	while(*pdat != '\0') {
		++pdat;
		++ret;
	}
	return ret;
}

//回调
void web_appcall(void)
{
	unsigned int size = 0;

	//连接成功
	if(w5500_connect()) {

	}
	//断开连接
	if(w5500_disconnect()) {
		web_reset();
	}
	//发送成功
	if(w5500_sendok()) {

	}
	//接收成功
	if(w5500_recvok()) {
		//从缓冲区中读取数据
		size = socket_recv(SOCKET0, buffer, 350);
		//检查HTTP头
		if(!check_http_header(buffer, size)) {
			web_reset();
			return;
		}
		size = __strlen(webdata);
		//回应HTTP请求数据
		socket_send(SOCKET0, webdata, size);
		web_reset();
	}
	//超时
	if(w5500_timeout()) {
		web_reset();
	}
}